﻿using System;

using System.Web.Http.Controllers;

namespace Cypher.Core
{
	public abstract class CypherService : ICypherService, System.Web.Http.Controllers.IHttpController
	{
		#region Properties

		/// <summary>
		/// Provides an object representation of a uniform resource identifier (URI)
		/// and easy access to the parts of the URI.
		/// </summary>
		protected Uri RequestUri { get; private set; }

		#endregion

		#region ICypherService Members

		public abstract ICypherResource CreateResourceListing(object provider);

		#endregion

		#region IHttpController Members

		System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> System.Web.Http.Controllers.IHttpController.ExecuteAsync(System.Web.Http.Controllers.HttpControllerContext controllerContext, System.Threading.CancellationToken cancellationToken)
		{
			// Set some information about the current request uri
			this.RequestUri = controllerContext.RequestContext.Url.Request.RequestUri;						
						
			// Get an instance to the current DocumentationProvider service registrated, 
			// if non registred, provider is null
			var provider = controllerContext.Configuration.Services.GetService(typeof(System.Web.Http.Description.IDocumentationProvider)) as System.Web.Http.Description.IDocumentationProvider;

			// create the service response message
			var response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK);
			response.Content = new System.Net.Http.ObjectContent<ICypherResource>(this.CreateResourceListing(provider), new System.Net.Http.Formatting.JsonMediaTypeFormatter());
			response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/json");

			return System.Threading.Tasks.Task.FromResult(response);
		}

		#endregion
	}
}
